package in.co.codedoc.struts;

import in.co.codedoc.json.JSONObjectValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.components.Component;

import com.opensymphony.xwork2.util.ValueStack;

public abstract class JSONStrutsComponentBase
	extends Component
{
	protected JSONStrutsComponentBase(ValueStack stack)
	{
		super(stack);
	}

	protected void SetPropertyValues(String namePrefix, JSONObjectValue jsonObject)
	{
		Collection<String> propertyNames = ((JSONObjectValue)jsonObject).GetPropertyNames(null);
		
		for(String propertyName:propertyNames)
		{
			SetValue
			(
				!namePrefix.equals("")
					? namePrefix + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1)
					: propertyName,
				((JSONObjectValue)jsonObject).GetProperty(propertyName)
			);
		}
		
		SetValue(namePrefix + "PropertyNames",propertyNames);		
	}
	
	@SuppressWarnings("unchecked")
	protected void SetValue(String name,Object value)
	{		
		String attrName = "#attr['" + name + "']";
		
		Object oldValue = stack.findValue(attrName);
		if(oldValue != null && oldValues != null)
		{
			oldValues.put(name, oldValue);
		}
		
		stack.getContext().put(name,value);
		stack.setValue(attrName,value);
		
		setNames.add(name);
	}

	protected void UnsetValues()
	{
		for(String name:setNames)
		{
			String attrName = "#attr['" + name + "']";
			
			if(oldValues.containsKey(name))
			{
				stack.setValue(attrName,oldValues.get(name));
			}
			
			stack.getContext().remove(name);
		}
	}
	

	private ArrayList<String> setNames = new ArrayList<String>(); 
	private Map<String,Object> oldValues = new HashMap<String, Object>();
}
